#pragma once
#include <iostream>
#include <memory>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Logger.hpp"
#include "AddInet.hpp"
#include <functional>

using callback =std:: function<void(std::string message)>;

const static int initfd = -1;

class ChatServer
{
public:
    ChatServer(uint16_t port,callback cb)
        : _socketfd(initfd), _port(port),_cb(cb), _isrunning(false)
    {
    }
    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(Loglevel::FATLA) << "socket创建失败";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket创建成功";
        AddInet local(_port);
        int n = bind(_socketfd, local.Addr(), local.Len());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind失败";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind成功";
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                AddInet clientaddr(peer);
                LOG(LogLevel::DEBUG) << "获取到了客户端输入：" << clientaddr.Ip() << " - " << clientaddr.Port() << ":" << buffer;
                std::string message=buffer;
                _cb(message);
            }
        }
    }
    void Stop()
    {
        _isrunning=false;
    }
    ~ChatServer() {}

private:
    int _socketfd;
    uint16_t _port;
    callback _cb;
    bool _isrunning;
};